package uploader

import (
    "fmt"
    "log"
    "os"
    "path"
    "strings"
    "time"
    "upload-ftp/config"
)

func Run() {
    go filterFile()
    upload()
}

func filterFile() {
    for {
        select {
        case p := <-FileChan:
            go func(pp PathStruct) {
                time.Sleep(2 * time.Second)
                _, err := os.Stat(pp.Path)
                if err != nil {
                    //log.Println("upload stat  error :", err)
                    return
                }
                UploadChan <- pp
            }(p)
        }
    }
}

func upload() {
    root := os.Getenv("WORK_DIR")
    ftp, err := ConnectFtp()
    if err != nil {
        log.Panicln("ftp 连接失败", err)
    }
    ftpRootPath := config.Ftp.RootPath
    sp := string(os.PathSeparator)
    for {
        pa := <-UploadChan
        relPath := strings.Replace(pa.Path, root, "", 1)
        relPath = strings.TrimLeft(relPath, sp)
        relPath = strings.ReplaceAll(relPath, sp, "/")
        uploadPath := fmt.Sprintf("%s%s", ftpRootPath, relPath)
        uploadDir := path.Dir(uploadPath)
        //log.Println("要上传的目录！", uploadDir)
        err := ftp.MKDir(uploadDir)
        if err != nil {
            if IsConnErr(err) {
                //log.Println("ftp 连接丢失，计划重连")
                ftp.reConnect()
                UploadChan <- pa
            } else {
                log.Println("创建目录失败!", err)
            }
            continue
        }
        // 大小一致不上传
        size, err := ftp.Client.FileSize(uploadPath)
        if err == nil && size == pa.Size {
            //log.Println("大小一致不重新上传", uploadPath)
            continue
        }
        log.Println("文件", pa.Op, pa.Path)
        fp, err := os.Open(pa.Path)
        if err != nil {
            log.Println(err, pa)
            continue
        }
        //log.Println("开始上传文件:", pa.Path, relPath)
        err = ftp.Client.Stor(uploadPath, fp)
        if err != nil {
            log.Println("上传失败", uploadPath, err)
        } else {
            log.Println("上传成功", uploadPath)
        }
        fp.Close()
    }

}
